package 线程池.ThreadLocal;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author caihe
 * @date 2022/8/22 17:13
 */
public class ThreadLocalTest {

    @Data
    static class Foo {
        // 实例总数
        static final AtomicInteger AMOUT = new AtomicInteger(0);
        // 实例编号
        int index = 0;
        // 对象内容
        int bar = 10;

        public Foo() {
            index = AMOUT.incrementAndGet();
        }
        
        @Override
        public String toString() {
            return "Foo{" +
                    "index=" + index +
                    ", bar=" + bar +
                    '}';
        }
    }
    
//    private static final ThreadLocal<Foo> LOCAL_FOO = new ThreadLocal<>();
    private static final ThreadLocal<Foo> LOCAL_FOO = ThreadLocal.withInitial(()->new Foo());

    public static void main(String[] args) {
        Log log = LogFactory.get();
        ExecutorService executor = ThreadUtil.newExecutor(5);
        for (int i = 0; i < 5; i++) {
            
            executor.execute(() -> {
                // 获取当前线程的本地变量
//               if (LOCAL_FOO.get() == null) {
//                   LOCAL_FOO.set(new Foo());
//               }
               log.info("初始的本地值：{}", LOCAL_FOO.get());
                // 每个线程执行10次
                for (int j = 0; j < 10; j++) {
                    Foo foo = LOCAL_FOO.get();
                    foo.setBar(foo.getBar() + 1);
                    ThreadUtil.sleep(10);
                }
                log.info("累加10次后本地值：{}" , LOCAL_FOO.get());
                // 删除 线程本地变量 中所绑定的值
                LOCAL_FOO.remove();
            });
        }
        
    }
    
}
